﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace AzureToolkit
{
    public class MessageClient
    {
        private MessageClientSettings _settings;

        public MessageClient()
        {
            _settings = new MessageClientSettings();
        }

        public MessageClient(MessageClientSettings settings)
        {
            _settings = settings;
        }

        public void AddMessage<TMessage>(TMessage message) where TMessage : IAzureQueueMessage
        {
            AddMessage<TMessage>(message, null);
        }

        public void AddMessage<TMessage>(TMessage message, string queueName) where TMessage : IAzureQueueMessage
        {
            var queue = new AzureQueue<TMessage>(_settings.Account, queueName);
            queue.AddMessage(message);
        }

        [Obsolete("Use overload TMessage string instead.")]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public void AddMessage<TMessage>(string queueName, TMessage message) where TMessage : IAzureQueueMessage
        {
            AddMessage<TMessage>(message, queueName);
        }

        public void AddMessageAsync<TMessage>(TMessage message) where TMessage : IAzureQueueMessage
        {
            AddMessageAsync<TMessage>(message, null);
        }

        public void AddMessageAsync<TMessage>(TMessage message, string queueName) where TMessage : IAzureQueueMessage
        {
            var queue = new AzureQueue<TMessage>(_settings.Account, queueName);
            queue.AddMessageCompleted += (sender, e) =>
            {
                if (AddMessageCompleted != null)
                {
                    var args = new QueueMessageEventArgs<IAzureQueueMessage>(e.Error, e.Cancelled, e.UserState, e.Message);
                    AddMessageCompleted(this, args);
                }
            };
            queue.AddMessageAsync(message);
        }

        public event EventHandler<QueueMessageEventArgs<IAzureQueueMessage>> AddMessageCompleted;
    }
}
